#include "handlers.h"
#include "../QCommon/user.h"
#include "../QCommon/QCommon.h"
#include "../QCommon/events.h"
#include "Discover.h"
#include <string>
#include <stdio.h>
#include <string.h>
#include <sys/msg.h>

using namespace std;

extern Notify *notify;
extern Discover *discover;

void MsgHandler::handle(AbstractEvent &e)
{
    MsgEvent &event=(MsgEvent&)e;
    cout<<event.name<<" ("<<event.src_ip<<' '<<event.src_pid<<") says:"<<endl;
    cout<<event.content<<endl;
}

void NetworkHandler::handle(AbstractEvent &e)
{
    NetworkEvent &event=(NetworkEvent&)e;
    User *user=new User();
    user->name=(string)event.name;
    user->ip=(string)event.src_ip;
    user->pid=event.src_pid;
    user->gender=event.gender;
    user->status=event.status;
    discover->setOnline(*user);
}

char* getfilepath(FileAskEvent *e)
{
    static char *buf=new char[100];
    cout<<e->name<<" ("<<e->src_ip<<' '<<e->src_pid<<") sends: "<<e->file_name<<endl;
    if(mkfifo(Q_SYN,0666)==-1)
        return NULL;

    cout<<"Receive ?<Y/N>";
    cout.flush();
    int fd=open(Q_SYN,O_RDWR);
    if(fd<=0)
        return NULL;
    read(fd,buf,FileAskEvent::MAX_LENGTH_FILE_NAME);
    close(fd);
    remove(Q_SYN);
    if(buf[0]=='#')
        return NULL;
    return buf;
}

void FileAskHandler::handle(AbstractEvent &e)
{
    int fd=retrieve_msqid();
    FileAskEvent *fae=(FileAskEvent*)&e;
    FileAnswerEvent ae;
    strcpy(ae.src_ip,fae->dest_ip);
    strcpy(ae.dest_ip,fae->src_ip);
    ae.src_pid=fae->dest_pid;
    ae.dest_pid=fae->src_pid;
    strcpy(ae.file_name,fae->file_name);
    char *file=getfilepath(fae);
    if(file!=NULL)
    {
        strcpy(ae.store_name,file);
        ae.answer_type=allow;
    }
    else
    {
        ae.answer_type=reject;
    }
    msgsnd(fd,&ae,size_event(ae)-sizeof(long),0);
}

void FileAnswerHandler::handle(AbstractEvent &e)
{
    cout<<"fileanswer..."<<endl;
}
